﻿using System.Linq;
using Samples.Radio.Agent;
using Samples.Radio.Data;

namespace Samples.Radio.Pages.Program
{
    public class ProgramPageViewModel:ViewModelBase
    {
        public string SelectedProgramName { get; set; }

        private ProgramViewModel _CurrentProgram;

        public ProgramViewModel CurrentProgram
        {
            get { return _CurrentProgram; }
            set
            {
                if (CurrentProgram == value) return;
                _CurrentProgram = value;
                RaisePropertyChanged(() => CurrentProgram);
            }
        }

        private PodcastViewModel _SelectedPodcast;

        public PodcastViewModel SelectedPodcast
        {
            get { return _SelectedPodcast; }
            set
            {
                if (SelectedPodcast == value) return;
                _SelectedPodcast = value;
                RaisePropertyChanged(() => SelectedPodcast);
            }
        }
        
        

        public ProgramPageViewModel(RadioRepository repository, IDispatcher dispatcher, INavigation navigation)
            : base(repository, dispatcher, navigation)
        {
            AddEventWiring(() => Repository.LoadProgramsCompleted += LoadProgramsCompleted,
                   () => Repository.LoadProgramsCompleted -= LoadProgramsCompleted);
        }

        private void LoadProgramsCompleted(object sender, ParameterEventArgs<ProgramViewModel[]> e)
        {
            if (e == null || e.Parameter1 == null)
            {
                // TODO: Handle errors in loading program data
                return;
            }

            CurrentProgram = (from p in e.Parameter1
                              where p.ProgramName == SelectedProgramName
                              select p).FirstOrDefault();


        }

        public override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs navigationEventArgs, System.Windows.Navigation.NavigationContext context, System.Collections.Generic.IDictionary<string, object> pageState)
        {
            base.OnNavigatedTo(navigationEventArgs, context, pageState);

            SelectedProgramName = context.QueryString["ProgramName"];

            Repository.LoadPrograms();
        }

        public void AddSelectedPodcast()
        {
            if (SelectedPodcast == null) return;
            Repository.AddPodcastToPlaylist(SelectedPodcast);
            SelectedPodcast = null;
        }
    }
}
